﻿using PFMCandidate;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PFMHandlers
{
   public  class PFMFileHandler:PFMHandler 
    {
       
       public override byte[] Perform(Candidate  aCandidate, byte[] fileByteArray)
        {
            if (fileByteArray == null)
            {

                return FileToBinary(aCandidate);
            }
            else
            {
                BinaryToFile(aCandidate, fileByteArray);
            }
            return null;
        }
        /// <summary>
        /// 将传进来的文件转换成字符串
        /// </summary>
        /// <param name="FilePath">待处理的文件路径(本地或服务器)</param>
        /// <returns></returns>
       public byte[] FileToBinary(Candidate FilePath)
        {
            FileStream fs = new FileStream(FilePath.Name, FileMode.Open, FileAccess.Read);
           // StreamReader m_streamReader = new StreamReader(fs); 
           //m_streamReader.BaseStream.Seek(0, SeekOrigin.Begin); 
           //PFMGlobals.PFMDefinitions.strLine = m_streamReader.ReadLine();

            //利用新传来的路径实例化一个FileStream对像
            int fileLength = Convert.ToInt32(fs.Length);
            //得到对像大小
            byte[] fileByteArray = new byte[fileLength];
            //声明一个byte数组
            BinaryReader br = new BinaryReader(fs);
            //声明一个读取二进流的BinaryReader对像
           for(int i=0;i<fileLength;i++){
               br.Read(fileByteArray, 0, fileLength);
                //将数据读取出来放在数组中
           }
            //string strData = Convert.ToBase64String(fileByteArray);
            //将数组转换为String字符串
            return fileByteArray;
        }
        /// <summary>
        /// 将传进来的字符串保存为文件
        /// </summary>
        /// <param name="path">需要保存的位置路径</param>
        /// <param name="binary">需要转换的字符串</param>
       public void BinaryToFile(Candidate path, byte[] binary)
        {
            FileStream fs = null;
           if(path.ProcessedName==null)
           {
               fs = new FileStream(path.Target.Dir, FileMode.Create, FileAccess.Write);
           }
           else
           {
                fs = new FileStream(path.Target.Dir + @"\" + path.ProcessedName, FileMode.Create, FileAccess.Write);
           }
            //利用新传来的路径实例化一个FileStream对像
            BinaryWriter bw = new BinaryWriter(fs);
            //实例化一个用于写的BinaryWriter
            string strData = Convert.ToBase64String(binary);
            bw.Write(Convert.FromBase64String(strData));
            byte[] a = Convert.FromBase64String(strData);

            bw.Close();
            fs.Close();
        }


    }
}
